package xcmg.device.service.warehouse;

import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.warehouse.MaterialTransferDO;
import xcmg.device.dao.entity.warehouse.MaterialTransferDetailDO;
import xcmg.device.dao.mapper.warehouse.MaterialTransferDetailMapper;
import xcmg.device.dao.mapper.warehouse.MaterialTransferMapper;
import xcmg.device.infra.DateUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.enums.BillDesc;
import xcmg.device.service.GenDocumentService;
import xcmg.device.service.company.CompanyInfoService;
import xcmg.device.service.vo.warehouse.MaterialTransferAddVO;
import xcmg.device.service.vo.warehouse.MaterialTransferDetailVO;
import xcmg.device.service.vo.warehouse.MaterialTransferVO;
import yb.ecp.fast.dto.UserCacheDTO;
import yb.ecp.fast.feign.AuthClient;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.PageHelperPlus;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MaterialTransferService {

    @Autowired
    private MaterialTransferMapper materialTransferMapper;

    @Autowired
    private MaterialTransferDetailMapper materialTransferDetailMapper;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private FastGenClient fastGenClient;

    @Autowired
    private GenDocumentService genDocumentService;

    @Autowired
    private AuthClient authClient;

    @Autowired
    private MaterialTransferAsyncService materialTransferAsyncService;

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode addPre(MaterialTransferAddVO transferAddVO, String userId, String orgId)throws Exception{
        String preSapArea = transferAddVO.getHeaderInfo().getPreSapArea()==null?"":transferAddVO.getHeaderInfo().getPreSapArea();
        String newSapArea = transferAddVO.getHeaderInfo().getNewSapArea()==null?"":transferAddVO.getHeaderInfo().getNewSapArea();
        if(StringUtil.isNullOrEmpty(preSapArea) || StringUtil.isNullOrEmpty(newSapArea) || preSapArea.equals(newSapArea)){
            transferAddVO.getHeaderInfo().setStatus(1);
            transferAddVO.getHeaderInfo().setSapStatus(3);
            return this.addSyn(transferAddVO, userId, orgId);
        }else{
//            try {
//                this.sapPost(transferAddVO, orgId);
//            }catch (Exception e){
//                materialTransferAsyncService.addAsync(transferAddVO, userId, orgId);
//                throw new Exception(e.getMessage());
//            }
            return this.addSyn(transferAddVO, userId, orgId);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode addSyn(MaterialTransferAddVO transferAddVO, String userId, String orgId)throws Exception{
        if(transferAddVO == null || ListUtil.isNullOrEmpty(transferAddVO.getDetailList())){
            return ErrorCode.IllegalArument;
        }
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode()){
            return ErrorCode.IllegalArument;
        }
        UserCacheDTO userInfo = authClient.getUserDetail(userId).getValue();
        if(userInfo == null){
            return ErrorCode.IllegalArument;
        }
        MaterialTransferVO transferVO = transferAddVO.getHeaderInfo();
        MaterialTransferDO transferDO = new MaterialTransferDO();
        BeanUtils.copyProperties(transferVO, transferDO);
        transferDO.setId(textResult.getValue());
        transferDO.setTransferOrder(genDocumentService.getDocumentNo(BillDesc.MaterialTransfer));
        transferDO.setDeptId(userInfo.getDeptId());
        transferDO.setDeptName(userInfo.getDeptName());
        transferDO.setCreateId(userId);
        transferDO.setCreateName(userInfo.getName());
        transferDO.setCreateDate(new Date());
        transferDO.setOrgId(orgId);

        boolean success = materialTransferMapper.insert(transferDO)>0;
        if(success){
            for(MaterialTransferDetailVO detailVO : transferAddVO.getDetailList()){
                MaterialTransferDetailDO detailDO = new MaterialTransferDetailDO();
                BeanUtils.copyProperties(detailVO, detailDO);
                detailDO.setId(fastGenClient.textGuid().getValue());
                detailDO.setTransferOrder(transferDO.getTransferOrder());
                detailDO.setOrgId(orgId);
                detailDO.setCreateId(transferDO.getCreateId());
                detailDO.setCreateName(transferDO.getCreateName());
                detailDO.setCreateDate(transferDO.getCreateDate());
                success = materialTransferDetailMapper.insert(detailDO)>0;
                if(!success){
                    throw new Exception("生成转库单详情记录失败");
                }
            }
        }
        return success?ErrorCode.Success:ErrorCode.Failure;
    }

    /**
     * @Author: WangKe
     * @Description: 获取转库单列表
     * @Date: 2018/7/19 0019
     */
    public PageCommonVO list(SearchCommonVO<MaterialTransferVO> condition) {
        PageCommonVO<MaterialTransferVO> pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<MaterialTransferDO> doList = materialTransferMapper.list(condition.getFilters());
        List<MaterialTransferVO> voList = new ArrayList<>();
        for (MaterialTransferDO entity : doList) {
            MaterialTransferVO model = new MaterialTransferVO();
            BeanUtils.copyProperties(entity, model);
            voList.add(model);
        }
        pageCommonVO.setPageInfo(new PageInfo(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    /**
     * @Author: WangKe
     * @Description: 根据主键或者调拨单号获取实体和详情
     * @Date: 2018/7/19 0019
     */
    public MaterialTransferAddVO findByPK(String id, String orgId){
        MaterialTransferAddVO model = new MaterialTransferAddVO();
        MaterialTransferDO entity = materialTransferMapper.selectByPrimaryKey(id);
        if(entity == null){
            return null;
        }

        PageHelperPlus.orderBy("create_date desc");
        List<MaterialTransferDetailDO> doList = materialTransferDetailMapper.list(entity.getTransferOrder(), orgId);
        List<MaterialTransferDetailVO> voList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(doList)){
            MaterialTransferDetailVO MaterialTransferDetailVO;
            for(MaterialTransferDetailDO detailDO : doList){
                MaterialTransferDetailVO = new MaterialTransferDetailVO();
                BeanUtils.copyProperties(detailDO, MaterialTransferDetailVO);
                voList.add(MaterialTransferDetailVO);
            }
        }
        MaterialTransferVO MaterialTransferVO = new MaterialTransferVO();
        BeanUtils.copyProperties(entity, MaterialTransferVO);

        model.setHeaderInfo(MaterialTransferVO);
        model.setDetailList(voList);
        return model;
    }

    /**
     * @Author: WangKe
     * @Description: 导出转库单记录
     * @Date: 2018/7/19 0019
     */
    public void export(List<String> ids)throws Exception{
        invokeExport(materialTransferMapper.findByIds(ids));
    }

    /**
     * @Author: WangKe
     * @Description: 导出全部转库单记录
     * @Date: 2018/7/19 0019
     */
    public void exportAll(MaterialTransferVO condition)throws Exception{
        Integer count = materialTransferMapper.findCountForExportAll(condition);
        List<MaterialTransferDO> dataList = new ArrayList<>();
        int times = count/500+1;
        for(int i=0; i<times; i++){
            PageHelperPlus.startPage(i + 1, 500, "create_date desc");
            dataList.addAll(materialTransferMapper.list(condition));
        }
        invokeExport(dataList);
    }

    /**
     * @Author: WangKe
     * @Description: 导出转库单记录
     * @Date: 2018/7/19 0019
     */
    private void invokeExport(List<MaterialTransferDO> doList)throws Exception{
        String title = "转库单数据导出";
        String[] rowsName = new String[]{"序号","转库单号","转库类型",
                "原储位","新储位", "制单时间", "制单部门", "制单人", "SAP同步状态",
                "零件凭证", "SAP错误信息"};
        List<Object[]>  dataList = new ArrayList<>();
        Object[] objs;
        for (int i = 0; i < doList.size(); i++) {
            MaterialTransferDO exportDO = doList.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i+1;
            objs[1] = exportDO.getTransferOrder();
            objs[2] = exportDO.getType()==0?"零件转移":"储位转移";
            objs[3] = exportDO.getPreLocationCode();
            objs[4] = exportDO.getNewLocationCode();
            objs[5] = DateUtil.formatDateTime(exportDO.getCreateDate());
            objs[6] = exportDO.getDeptName();
            objs[7] = exportDO.getCreateName();
            objs[8] = getState(exportDO.getSapStatus());
            objs[9] = exportDO.getVoucherNo();
            objs[10] = exportDO.getSapErrorMsg();
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    private String getState(Integer state){
        if(state == null){
            state = 0;
        }
        if(state == 0 ){
            return "未同步";
        } else if (state == 1) {
            return "同步成功";
        } else if (state == 2) {
            return "同步失败";
        } else if (state == 3) {
            return "不需同步";
        }
        return "";
    }

//    public void sapPost(MaterialTransferAddVO transferAddVO, String orgId) throws Exception {
//        ImportParam importParam = fillImportParam(transferAddVO, orgId);
//        LogHelper.monitor("========调用移库过账接口开始========");
//        OutputParam outputParam = SAPCommonUtil.getData(importParam);
//        LogHelper.monitor("========调用移库过账接口结束========");
//        if (null == outputParam || outputParam.getCode() != 0) {
//            LogHelper.error("sap返回值为null", ErrorCode.RequestIdError.getCode());
//            throw new Exception("sap返回值为null");
//        }
//        if ("OK".equals(outputParam.getDataHeader().get("RETURNCODE").toUpperCase())) {
//            if(StringUtil.isNullOrEmpty(outputParam.getDataHeader().get("MBLNR"))){
//                throw new Exception("移库零件凭证号为空");
//            }
//            transferAddVO.getHeaderInfo().setSapStatus(1);
//            transferAddVO.getHeaderInfo().setStatus(1);
//            transferAddVO.getHeaderInfo().setVoucherNo(outputParam.getDataHeader().get("MBLNR"));
//        } else {
//            transferAddVO.getHeaderInfo().setSapStatus(2);
//            transferAddVO.getHeaderInfo().setStatus(2);
//            transferAddVO.getHeaderInfo().setSapErrorMsg(outputParam.getDataHeader().get("RETURNMSG"));
//            //返回处理的消息
//            throw new Exception(outputParam.getDataHeader().get("RETURNMSG"));
//        }
//    }
//
//    private ImportParam fillImportParam(MaterialTransferAddVO transferAddVO, String orgId) throws Exception {
//        CompanyInfoVO companyInfoVO = companyInfoService.info(orgId);
//        if (companyInfoVO == null || companyInfoVO.getSapCode() == null) {
//            LogHelper.error("企业不存在,orgId:" + orgId, ErrorCode.RequestIdError.getCode());
//            throw new Exception("企业不存在");
//        }
//        ImportParam importParam = new ImportParam();
//        importParam.setFunction("ZPMS_SET_MB1B");
//        Map<String, List<Map<String, String>>> tableParamMap = new HashMap<>();
//        List<Map<String, String>> dataList = new ArrayList<>();
//        for(MaterialTransferDetailVO detailVO : transferAddVO.getDetailList()){
//            Map<String, String> map = new HashMap<>();
//            map.put("WERKS", companyInfoVO.getSapCode());
//            map.put("MATNR", detailVO.getMaterialNo());
//            map.put("ERFMG", detailVO.getAmount()+"");
//            map.put("LGORT", transferAddVO.getHeaderInfo().getPreSapArea());
//            map.put("UMLGO", transferAddVO.getHeaderInfo().getNewSapArea());
//            dataList.add(map);
//        }
//        tableParamMap.put("INTAB", dataList);
//        importParam.setTableParamMap(tableParamMap);
//        importParam.setSapCode(companyInfoVO.getSapCode());
//        return importParam;
//    }
}
